//
//  YMultipleAlertController.swift
//  EasyEverything
//
//  Created by YangZhe on 17/4/19.
//  Copyright © 2017年 kuletech. All rights reserved.
//

import UIKit

open class YMultipleAlertController: UIAlertController,UITableViewDataSource,UITableViewDelegate {
    
    let cellIdentifier = "YMultipleAlertControllerCell"
    var tableView:UITableView?
    var dataSource = YOrderMap<String>()

    override open func viewDidLoad() {
        super.viewDidLoad()
        title = "\(title!)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
        tableView = UITableView(frame: CGRect(x: 0, y: 60, width: 270, height: 390))
        tableView?.backgroundColor = .clear
        tableView?.tableFooterView = UIView(frame: .zero)
        tableView?.bounces = false
        tableView?.dataSource = self
        tableView?.delegate = self
        tableView?.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        self.view.addSubview(tableView!)
    }
    
    open func setDataSource(dataSource:YOrderMap<String>, onConfirm:@escaping (YOrderMap<String>) -> ()) -> YMultipleAlertController{
        self.dataSource = dataSource
        tableView?.reloadData()
        addAction(UIAlertAction(title: "确定", style: .default, handler: { (_) in
            onConfirm(self.getSelectedDataSource())
        }))
        return self
    }
    
    func getSelectedDataSource() -> YOrderMap<String> {
        let selectedDataSource = YOrderMap<String>()
        for entity in dataSource.yOrderMapEntities {
            if entity.isChecked {
                selectedDataSource.put(entity.key, entity.value)
            }
        }
        return selectedDataSource
    }
    
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.yOrderMapEntities.count
    }

    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
        if cell == nil {
            cell = UITableViewCell(style: .default, reuseIdentifier: cellIdentifier)
            cell?.backgroundColor = .clear
        }
        let entity = dataSource.yOrderMapEntities[indexPath.row]
        cell?.textLabel?.text = entity.value
        cell?.accessoryType = entity.isChecked ? .checkmark : .none
        return cell!
    }
    
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        dataSource.yOrderMapEntities[indexPath.row].isChecked = !dataSource.yOrderMapEntities[indexPath.row].isChecked
        let cell = tableView.cellForRow(at: indexPath)
        cell?.accessoryType = dataSource.yOrderMapEntities[indexPath.row].isChecked ? .checkmark : .none
    }
}
